package comp.movel.ubiqua.ws;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Vector;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

public class ConexaoWebService {
	private static final String URL = "http://www.renanbandeira.com.br/smm/wsdlpassaourepassa.php";
	private static final String OPERATION = "buscaPerguntaPorId";
	private static final String NAMESPACE = "urn:passaourepassawsdl";

	public static PerguntaWSDL getPergunta(int id) throws IOException,
			XmlPullParserException {
		SoapObject request = new SoapObject(NAMESPACE, OPERATION);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		request.addProperty("id", id);
		envelope.addMapping(NAMESPACE, "pergunta",
				new PerguntaWSDL().getClass());
		envelope.setOutputSoapObject(request);
		HttpTransportSE httpTransport = new HttpTransportSE(URL);
		httpTransport.debug = true;
		httpTransport.call("", envelope);
		PerguntaWSDL pergunta = (PerguntaWSDL) envelope.getResponse();
		return pergunta;
	}

	public static ArrayList<JogadorWSDL> recebeRanking() throws IOException,
			XmlPullParserException {
		SoapObject request = new SoapObject(NAMESPACE, "recebeRanking");
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.addMapping(NAMESPACE, "jogador", new JogadorWSDL().getClass());
		envelope.setOutputSoapObject(request);
		HttpTransportSE httpTransport = new HttpTransportSE(URL);
		httpTransport.debug = true;
		httpTransport.call("", envelope);
		Vector a = (Vector) envelope.getResponse();
		ArrayList<JogadorWSDL> ranking = new ArrayList<JogadorWSDL>();
		for (int i = 0; i < a.size(); i++) {
			ranking.add((JogadorWSDL) a.get(i));
		}
		return ranking;
	}

	public static String atualizaRanking(String nome, int pontuacao)
			throws IOException, XmlPullParserException {
		SoapObject request = new SoapObject(NAMESPACE, "atualizaRanking");
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.addMapping(NAMESPACE, "jogador", new JogadorWSDL().getClass());
		request.addProperty("jogador", new JogadorWSDL(nome, pontuacao));
		envelope.setOutputSoapObject(request);
		HttpTransportSE httpTransport = new HttpTransportSE(URL);
		httpTransport.debug = true;
		httpTransport.call("", envelope);
		Object a = (Boolean) envelope.getResponse();
		return a.toString();
	}
}
